import React, { useState,useEffect } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Typography } from 'antd';
import './index.css';

import {getAuthList,addAuth}from '../../../api/auth'

let originData = [];

/**
 * 数据
 */
for (let i = 0; i < 100; i++) {
  originData.push({
    key: i.toString(),
    id: `Edrward ${i}`,
    name: 32,
    state: `London Park no. ${i}`,
  });
}

/**
 * 
 * TODO 
 */

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
}; 

/**
 * 
 * @returns TODO
 */

const EditableTable = (props) => {

 
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState('');
  let [searchsta,setSearchasta]=useState({id:'',name:''});

  const isEditing = (record) => record.key === editingKey;

  searchsta={id:props.store.search.id,name:props.store.search.name};

  //接受到添加的obj
  let obj=props.store.addObj;

  useEffect(()=>{
    if(obj){

      addAuth(obj).then((data)=>{
        console.log("添加",data)

      })

    }
 

  },[obj]);
  
  useEffect(()=>{

    //判断单值查询里面是否有值
    let isId=false;
    let isName=false;
    isId=searchsta.id!==''?true:false;
    isName=searchsta.name!==''?true:false;
    let newData=[];//存储查询到的值
    //只要有一个为真都执行查询逻辑

    console.log("判断郑家",isId,isName);
    if(isId || isName) {

      newData= originData.filter((item)=>{
        if(isId){
         
          isId=searchsta.id===item.id?true:false;
          console.log("id相同",searchsta.id,item.id,isId)
        }
        if(isName){
     
          isName=searchsta.name===item.name?true:false;
          console.log("name相同",isName && isId)
        }
        return isId&&isName;
      })
      //c
    }
    console.log("过滤后的值",newData);
    if(newData.length===0){

      setData(originData);
    }else{
      setData(newData);
    }
    

  },[searchsta]);

  //获取数据
  useEffect(()=>{
    getAuthList().then((data)=>{

        // key: i.toString(),
        // id: `Edrward ${i}`,
        // name: 32,
        // state: `London Park no. ${i}`,

        originData=data.data;
        const newOri= originData.map((item,index)=>{

            item.key=index+1+"";
            item.id=item.id;
            item.name=item.name;
            item.state=item.status?"开启":"关闭";
        
          console.log(item);
            return item;
        }) 
        setData(newOri);
      
    })
  },[obj])

  const edit = (record) => {
    form.setFieldsValue({
      ID: '',
      名称: '',
      状态: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  function del(data){

    //直接过滤掉id
    const newData=originData.filter((item)=>{
      if(item.id !== data.id){
        return item;
      }
    
    })
    console.log("过滤后的数据",newData);
    originData=newData;
    setData(newData);
  
  
  
  }

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: '25%',
      editable: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: '15%',
      editable: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: '40%',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a
              href="javascript:;"
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              Save
            </a>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
          <>
           <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
            Edit
          </Typography.Link>
          <span>&nbsp;&nbsp;</span>
          <Typography.Link onClick={() => del(record)}>
            Del
          </Typography.Link>
          </>
         
          
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{
          onChange: cancel,
        }}
      />
    </Form>
  );
};

export default EditableTable;


